import {
  controlSuffix,
  viewSuffix,
  EVENT_CONFIG_MSG,
  EVENT_INTI_CONFIG,
  EVETN_CONTROL_CONFIG_MSG,
  EVENT_SCREEN_TO_CONFG,
  EVENT_LEAVE_PAGE,
} from "../constant";
import { event } from "./event";
import config from "../../../config";
import { storage, getScreenInfo, debound } from "./utils";
import Strategy from "./strategy";
class CommunicationLocal extends Strategy {
  clientName = "tab";
  // 是否发送了首次的配置信息
  isFirsetSendConfig = false;
  constructor(id, options) {
    super(id, options);
    window.addEventListener("storage", this.onMessage);
    window.addEventListener("beforeunload", this.onBeforeunload);
    if (!this.options.isControl) {
      window.addEventListener("resize", this.doPublishScreenOptions);
    }
  }

  onMessage = (event) => {
    // 状态确认
    const topic = event.key;
    if (topic === this.topicState) {
      this.towHandshake(event);
      return;
    }

    if (topic === this.topicMsg) {
      this.onConfig(event);
      return;
    }

    if (topic === this.topicScreen) {
      console.log("收到屏幕信息");
      const data = JSON.parse(event.newValue);
      this.dispatch(EVENT_SCREEN_TO_CONFG, data);
    }

    if (topic === this.topicLeave) {
      const data = JSON.parse(event.newValue);
      this.dispatchLevae(data.username);
    }
  };

  towHandshake(event) {
    const data = JSON.parse(event.newValue);

    const { username, isControl, toname } = data;

    // 二次接收确认了

    if (toname === this.username) {
      this.pushUserName({ isControl, username });
      this.dispatchResolve(data);
      return;
    }

    // 放映端接收控制端的数据
    if (isControl && !this.options.isControl) {
      this.pushUserName({ isControl, username });

      this.dispatchResolve(data);
      this.doPublishState({
        toname: username,
      });
    }

    // 控制端接收放映端的数据
    if (!isControl && this.options.isControl) {
      this.pushUserName({ isControl, username });

      this.dispatchResolve(data);
      this.doPublishState({
        toname: username,
      });
    }
  }

  onConfig(event) {
    const data = JSON.parse(event.newValue);
    const { username, isControl } = data;
    if (username === this.username) return;
    if (!this.options.isControl) {
      this.dispatch(EVENT_CONFIG_MSG, data);
    }

    if (this.options.isControl && isControl) {
      this.dispatch(EVETN_CONTROL_CONFIG_MSG, data);
    }
  }

  check(resolve) {
    this.doPublishState();
    this.resolve = resolve;
  }

  doPublishState(payload = {}) {
    storage.set(
      this.topicState,
      JSON.stringify({
        time: Date.now(),
        isControl: this.options.isControl,
        username: this.username,
        type: this.options.isControl ? controlSuffix : viewSuffix,
        ...payload,
      })
    );
  }

  dispatchResolve(data) {
    this.resolve(this);
    this.resolve.isExecute = true;

    setTimeout(() => {
      if (this.options.isControl) {
        if (this.isFirsetSendConfig) return;
        this.isFirsetSendConfig = true;
        const cconfig = storage.get(this.topicMsg)
          ? JSON.parse(storage.get(this.topicMsg))
          : {
              config,
              id: this.id,
              isControl: true,
              time: Date.now(),
            };

        this.dispatch(EVENT_INTI_CONFIG, cconfig);
      }

      if (!this.options.isControl && !this.firsetSendScreenOptionsUsername.includes(data.username)) {
        this.firsetSendScreenOptionsUsername.push(data.username);
        this.doPublishScreenOptions();
      }
    });
  }

  /**
   * 控制端向放映端发送消息
   */
  doPublishConfig(config) {
    this.doPublish(this.topicMsg, config);
  }

  destroy() {
    window.removeEventListener("storage", this.onMessage);
    window.removeEventListener("resize", this.doPublishScreenOptions);
    window.removeEventListener("beforeunload", this.onBeforeunload);
  }

  doPublishScreenOptions = debound(() => {
    const screenOptions = getScreenInfo();
    this.doPublish(this.topicScreen, screenOptions);
  }, 500);

  onBeforeunload = (event) => {
    event.returnValue = "关闭提示";
    this.doPublish(this.topicLeave, {});
    return "关闭提示";
  };

  doPublish(topic, payload = {}) {
    storage.set(
      topic,
      JSON.stringify({
        id: this.id,
        isControl: this.options.isControl,
        time: Date.now(),
        username: this.username,
        config: payload,
      })
    );
  }
}

export default CommunicationLocal;
